﻿using System;
using System.IO;

namespace Utility
{
    public static class StreamExtensions
    {
        public static void CopyTo(this Stream source, Stream destination)
        {
            source.CopyTo(destination, 8192);
        }

        public static void CopyTo(this Stream source, Stream destination, int chunkSize)
        {
            if (source == null)
                throw new ArgumentNullException("source");
            if (destination == null)
                throw new ArgumentNullException("destination");
            if (!source.CanRead)
                throw new InvalidOperationException("Source Stream cannot be read");
            if (!destination.CanWrite)
                throw new InvalidOperationException("Destination Stream cannot be written");

            int readCount;
            var buffer = new byte[chunkSize];
            while ((readCount = source.Read(buffer, 0, buffer.Length)) != 0)
                destination.Write(buffer, 0, readCount);
        }

        public static void Rewind(this Stream stream)
        {
            stream.Seek(0, SeekOrigin.Begin);
        }
    }
}